<template>
	<a-modal v-bind="options" class="link-wirte-off-bill-record-dialog">
		<VxeGrid ref="bankRecordGrid" v-bind="bankRecordGridOptions">
			<template #top>
				<a-row type="flex" justify="space-between" align="middle">
					<a-typography-paragraph strong>
						<blockquote>银行账单流水</blockquote>
					</a-typography-paragraph>
					<a-col :span="5" class="justify-end">
						<span>银行流水总计：</span>
						<span v-color="{color: mapColorState(bankFlowTotal)}">{{ fixedTwo(bankFlowTotal) }}</span>
						<span>元</span>
					</a-col>
				</a-row>
			</template>
		</VxeGrid>
		<VxeGrid ref="compareContractList" v-bind="compareContractGridOptions">
			<template #top>
				<a-row type="flex" justify="space-between" align="middle">
					<a-typography-paragraph strong>
						<blockquote>合约账单</blockquote>
					</a-typography-paragraph>
					<a-col :span="5" class="justify-end">
						<span>已核账单总计：</span>
						<span v-color="{color: mapColorState(writeOffTotal)}">{{ fixedTwo(writeOffTotal) }}</span>
						<span>元</span>
					</a-col>
				</a-row>
			</template>

			<template #billStatus="{row}">
				<template v-if="row.billStatus === 1">
					<a-tag v-if="row.notOccurredMoney >= 0" color="processing">待收款</a-tag>
					<a-tag v-else color="error">待付款</a-tag>
					<small v-if="row.overdueDays" v-color="{color: 'danger'}">逾期{{ row.overdueDays }}天</small>
				</template>
				<template v-else-if="row.billStatus === 2">
					<a-tag color="success">已结清</a-tag>
				</template>
				<template v-else-if="row.billStatus === 9">
					<a-tag color="default">已作废</a-tag>
				</template>
			</template>
			<template #occurredMoneyTotal="{row}">
				<span v-if="0 === row.occurredMoneyTotal"></span>
				<span v-else v-color="{color: row.occurredMoneyTotal > 0 ? 'primary' : 'danger'}">{{ row.occurredMoneyTotal }}</span>
			</template>
			<template #expandContent="{row}">
				<VxeTable align="center" :data="row.billDetailList" :show-header="false">
					<VxeColumn width="150"></VxeColumn>
					<VxeColumn width="100"></VxeColumn>
					<VxeColumn width="350"></VxeColumn>
					<VxeColumn width="100" field="feeSubjectValue"></VxeColumn>
					<VxeColumn width="200">
						<template #default="{row: details}">
							<span>{{ formatRangeTime(details.beginTime, details.endTime) }}</span>
						</template>
					</VxeColumn>
					<VxeColumn align="right">
						<template #default="{row: details}">
							<span v-color="{color: amountColor(details)}">
								{{
									1 === details.feeDirection ? details.occurredMoney : `${amountSymbol(details)}${details.occurredMoney}`
								}}
							</span>
						</template>
					</VxeColumn>
				</VxeTable>
			</template>
		</VxeGrid>
		<template #footer></template>
	</a-modal>
</template>

<script lang="ts" setup>
	import {ref, reactive, watch, computed} from 'vue'
	import {VxeGridInstance, VxeGridProps} from 'vxe-table'
	import {amountColor, amountSymbol} from 'yuxin-base/src/utils'
	import DATE_FORMAT from 'yuxin-base/src/utils/date'
	import {getContractByVerifyId} from '@/api/bill'
	import dayjs from 'dayjs'

	const props = defineProps<{
		verifyId: string | null
	}>()

	const bankRecordGrid = ref<VxeGridInstance>()
	const enterpriseName = ref('')
	const bankFlowTotal = ref(0)
	const writeOffTotal = ref<string>('0')

	const mapColorState = (num: number | string) => {
		return Number(num) < 0 ? 'danger' : 'primary'
	}
	const formatRangeTime = (start, finish) => {
		const begin = start ? dayjs(start).format(DATE_FORMAT.DATE) : ''
		const end = finish ? dayjs(finish).format(DATE_FORMAT.DATE) : ''
		return `${begin} - ${end}`
	}

	const fixedTwo = computed(() => {
		return val => {
			return Number(val).toFixed(2)
		}
	})

	// 根据数据生成银行流水信息
	const createBankBillInfo = (data: object) => {
		const mapList = ['enterpriseName', 'paymentType', 'paymentAccount', 'payDate', 'payMoney', 'paymentNo', 'remark']
		const obj: any = {}
		mapList.forEach(i => {
			obj[i] = data[i]
		})
		bankRecordGridOptions.data = [obj]
		enterpriseName.value = obj.enterpriseName
		bankFlowTotal.value = +Number(obj.payMoney).toFixed(2)
	}

	const sumNum = (list: any[], field: string) => {
		let count = 0
		list.forEach(item => {
			if (item.feeDirection === 1) {
				count += Number(item[field])
			} else {
				count -= Number(item[field])
			}
		})
		return count.toFixed(2)
	}

	// 根据数据生成合约账单
	const getContract = (data: Array<any>) => {
		compareContractGridOptions.data = data.map(i => {
			i.billDetailList.forEach(j => {
				j.occurredMoney = j.occurredMoney.toFixed(2)
			})
			i.occurredMoneyTotal = sumNum(i.billDetailList, 'occurredMoney')
			return i
		})
		const getAllBillDetailList = compareContractGridOptions.data.reduce((prev, curr) => {
			return [...prev, ...curr.billDetailList]
		}, [])
		writeOffTotal.value = sumNum(getAllBillDetailList, 'occurredMoney')
	}

	// 获取合约账单
	const getData = () => {
		if (props.verifyId) {
			getContractByVerifyId(props.verifyId).then(res => {
				const {financeVerify, financeBillList} = res.data
				createBankBillInfo(financeVerify)
				getContract(financeBillList)
			})
		}
	}

	// 弹窗配置
	const options = reactive({
		width: 1100,
		title: '关联核销记录',
		maskClosable: false,
		centered: true,
		destroyOnClose: true,
		visible: true,
		bodyStyle: {
			padding: '0 24px'
		},
		onCancel: () => {}
	})

	// 表头(上)
	const bankRecordGridOptions = reactive<VxeGridProps>({
		height: '250',
		showOverflow: true,
		loading: false,
		align: 'center',
		size: 'small',
		rowConfig: {
			height: 40,
			isHover: true
		},
		columns: [
			{
				title: '企业名称',
				field: 'enterpriseName'
			},
			{
				title: '支付方式',
				field: 'paymentType'
			},
			{
				title: '支付账号',
				field: 'paymentAccount'
			},
			{
				title: '支付时间',
				field: 'payDate'
			},
			{
				title: '支付流水号',
				field: 'paymentNo'
			},
			{
				title: '备注',
				field: 'remark',
				formatter: ({cellValue}) => {
					return cellValue ? cellValue : '-'
				}
			}
		],
		data: []
	})

	// 表头(下)
	const compareContractGridOptions = reactive<VxeGridProps>({
		height: '250',
		showOverflow: true,
		align: 'center',
		size: 'small',
		rowConfig: {
			height: 40,
			isHover: true
		},
		expandConfig: {
			expandAll: true
		},
		columns: [
			{
				title: '状态',
				type: 'expand',
				slots: {
					default: 'billStatus',
					content: 'expandContent'
				},
				width: 150
			},
			{
				title: '企业名称',
				width: 100,
				formatter: ({cellValue}) => {
					return enterpriseName.value
				}
			},
			{
				title: '房源地址',
				field: 'fullHouseAddress',
				width: 350
			},
			{
				title: '账单摘要',
				field: 'billName',
				width: 100
			},
			{
				title: '账单周期',
				field: 'createTime',
				formatter: ({row}) => {
					return formatRangeTime(row.beginTime, row.endTime)
				},
				width: 200
			},
			{
				title: '待收（付）已核',
				slots: {
					default: 'occurredMoneyTotal'
				},
				align: 'right'
			}
		],
		data: []
	})

	watch(
		() => props.verifyId,
		val => {
			getData()
		},
		{deep: true}
	)
</script>

<style scoped>
	.ant-typography {
		margin-bottom: 0;
	}

	.justify-end {
		display: flex;
		justify-content: end;
	}
</style>
